import Vue from 'vue'
import dayjs from 'dayjs'
import command from '@/utils/command'
Vue.use(command)
const state = {
  member: localStorage.getItem('currentMember') ? JSON.parse(localStorage.getItem('currentMember')) : {},
  name: '',
  roles: [],
  messageStatus: false,
  belongStoreList: localStorage.getItem('belongStoreList') ? JSON.parse(localStorage.getItem('belongStoreList')) : [],
  currentStore: localStorage.getItem('selectStoreRole') ? JSON.parse(localStorage.getItem('selectStoreRole')) : { store: {} }
}
const mutations = {
  updateMember: (state, data) => {
    state.member = data
    state.name = data.staffName
  },
  updateRoles: (state, data) => {
    state.roles = data
  },
  setMessageStatus: (state, data) => {
    state.messageStatus = data
  }
}
const actions = {
  async get ({ commit, dispatch }) {
    if (Object.keys(state.member).length === 0) {
      const result = await command.executeCommand({
        api: '/admin-api/user/staff-info',
        parameter: {},
      })
      if (result.data && result.data.store && result.data.store.closeDate) {
        result.data.store.closeDate = dayjs.unix(result.data.store.closeDate).format('YYYY-MM-DD')
      }
      let data = result.data
      commit('updateMember', data)
    }
    return state
  },
  async setMemberInfo ({ commit, dispatch }, playLoad) {
    localStorage.setItem('currentMember', JSON.stringify(playLoad))
    commit('updateMember', playLoad)
  },
  async getStaffRoles ({ commit }) {
    if (Object.keys(state.member).length) {
      const result = await command.executeCommand({
        api: '/admin-api/user/staff/role',
        parameter: {},
      })

      let data = result.data
      commit('updateRoles', data)
    }
    return state
  }
}

export default {
  namespaced: true,
  mutations,
  state,
  actions,
}
